/*
 * JS for review system
 */

$(document).ready(function(){
    var brdrColor = $('.review-form').find('input:text:first').css('borderTopColor')
    $('.success,.errors').live('click',function(){
        $(this).hide().find('li').hide();
    });
    
    $('.review-form')
        .find(':input[name="name"],:input[name="email"],textarea[name="review-content"],#captcha-input')
        .change(function(){
        if (trim($(this).val())=='') {
            $(this).css({borderColor:'red'}).addClass('err');
        } else {
            $(this).css({borderColor:brdrColor}).removeClass('err');
        }
    })

    $('.review-form').submit(function(event){
        var errors = new Array();
        $('.reviewmsg div ul li').remove();
        $(".reviewmsg div").removeClass();
        var formId = $(this).attr('id')
        var websiteUrl = $("#hid-main-wsurl").val()
        event.preventDefault()
        if ($('.err',$(this)).size()){
            $('.err:first').focus();
            return false;
        }
        var productId = $(this).find('input[name="productId"]').val();
        $name = $('#review-name-'+productId);
        $email = $('#review-email-'+productId);
        $review = $('#review-content-'+productId);
        $captchaInp = $(this).find('#captcha-input')
        if (trim($name.val()) == ''){
            var emptyerror = '<li class="review-name-empty-error" >'+reviewFormMessages.nameemptyerror+'</li>';
            $name.focus().css({'borderColor':'red'}).addClass('err');
            errors.push(emptyerror);
            }
        if (trim($email.val()) == '') {
            var emailempty = '<li class="review-email-empty-error" >'+reviewFormMessages.emailemptyerror+'</li>';
            $email.focus().css({'borderColor':'red'}).addClass('err');
            errors.push(emailempty);
        } else {
            var email = trim($email.val());
            if (!email.match(/^[A-z0-9\._%+-]+@[A-z0-9\.-]+\.[A-z]{2,6}$/)){
                var emailregex = '<li class="review-email-regex-error" >'+reviewFormMessages.emailregexerror+'</li>';
                $email.focus().css({'borderColor':'red'}).addClass('err');
                errors.push(emailregex);
            }
        }
        if (trim($review.val()) == '') {
            var contentempty = '<li class="review-content-empty-error" >'+reviewFormMessages.reviewcontentemptyerror+'</li>';
            $review.focus().css({'borderColor':'red'}).addClass('err');
            errors.push(contentempty);
        }
        if (trim($captchaInp.val()) == ''){
            var captchaempty = '<li class="review-captcha-empty-error" >'+reviewFormMessages.reviewcaptchaemptyerror+'</li>';
            $captchaInp.focus().css({'borderColor':'red'}).addClass('err');
            errors.push(captchaempty);
        }
       
        if (errors.length>0){
            $(".reviewmsg div").addClass("errors");
            errors.reverse();
            for(i=0;i<errors.length;i++) {
                    $('.errors ul').prepend(errors[i]);
            }
            $('.errors').show();
            return false;
        };
        $(".reviewmsg div").removeClass().addClass("success");
        
        $('.success').ajaxStart(function(){
            $('.reviewmsg div ul li').remove();
            var proccessing = '<li class="proccessing" >'+reviewFormMessages.proccessing+'</li>';
            $('.success ul').prepend(proccessing);
            $(this).show();
        })
        $.ajax({
              url: ''+websiteUrl+'sys/backend_ajax/addreview/'
            , type: 'POST'
            , data: {
                  productId:productId
                , name: trim($name.val())
                , email: trim($email.val())
                , website: trim($('#review-website-'+productId).val())
                , topic: trim($('#review-topic-'+productId).val())
                , review_content: trim($review.val())
                , captcha_input: trim($captchaInp.val())
                , captcha_id: $(this).find('#captcha-id').val()
            }
            , dataType: 'json'
            , success: function(responce){
                
                if (responce.done) {
                    $('.reviewmsg div ul li').remove();
                       if (responce.html != '' && responce.prodid > 0){
                       $('#reviews-for-product-'+responce.prodid).prepend(responce.html);
                       $(this).find(':text,textarea').val('');
                       var added = '<li class="added">'+reviewFormMessages.added+'</li>';
                       $('.success ul').prepend(added);
                                             
                   } else {
                       var addedwait = '<li class="addedwait">'+reviewFormMessages.addedwait+'</li>';
                       $('.success ul').prepend(addedwait);
                       
                   }
                } else {
                    $('.reviewmsg div ul li').remove();
                    $(".reviewmsg div").removeClass().addClass("errors");
                    $('.errors').show();
                    switch (responce.msg){
                        case 'captcha error':
                            var captchainvalid = '<li class="review-captcha-invalid-error">'+reviewFormMessages.reviewcaptchainvaliderror+'</li>';
                            $('.errors ul').prepend(captchainvalid);
                            break;
                        default:
                            var unrecognizederror = '<li class="review-unrecognized-error">'+reviewFormMessages.reviewunrecognizederror+'</li>';
                            $('.errors ul').prepend(unrecognizederror);
                            break;
                    }
                }
                $(this).find('#captcha-image').attr('src',websiteUrl+'tmp/'+responce.captchaId+'.png');
                $(this).find('#captcha-id').val(responce.captchaId);
            }
            , error: function(){
                $(".reviewmsg div").removeClass().addClass("errors");
                var unrecognizederror = '<li class="review-unrecognized-error">'+reviewFormMessages.reviewunrecognizederror+'</li>';
                $('.errors ul').prepend(unrecognizederror);
                $('.errors').show();
            }
            , context: $(this)
        })


        });

    $('.vote-for-review').submit(function(event){
        event.preventDefault();
    })
    $('.vote-for-review-btn').live('click',function(){
        var websiteUrl = $("#hid-main-wsurl").val();
        var id = $('.vote-for-review').attr('name').replace('vote-for-review-','');
        var value = $(this).attr('name').replace('vote-','');

        $.ajax({
              url: websiteUrl+'sys/backend_ajax/voteforreview'
            , type: 'POST'
            , data: {value: value, reviewId: id}
            , dataType: 'json'
            , success: function(responce){
                if (responce.done){
                    if (undefined!==responce.id){
                        $('#rank-for-review-'+id).text(responce.rank);
                    }
                }
            }
            , context: $(this)
        })
    })
});

function deleteReview(id){
    $('.reviewmsg div ul li').remove();
    $(".reviewmsg div").removeClass().addClass("success");
    var websiteUrl = $("#hid-main-wsurl").val();
    $('.success').ajaxStart(function(){
        $('.reviewmsg div ul li').remove();
        var proccessing = '<li class="proccessing">'+reviewFormMessages.proccessing+'</li>';
        $('.reviewmsg div ul').prepend(proccessing);
        $(this).show();
        
    })
    $.ajax({
          url: ''+websiteUrl+'sys/backend_ajax/deletereview/'
        , type: 'POST'
        , data: {id: id}
        , dataType: 'json'
        , success: function(responce){
            $('.reviewmsg div ul li').remove();
            if (responce.done){
                $('#review-'+responce.id).remove();
                var status = '<li class="status">'+reviewFormMessages.status+'</li>';
                $('.success ul').prepend(status);
                $('.success ul').find('li.status').show().text('Review #'+responce.id+' deleted');
            } else {
                $(".reviewmsg div").removeClass();
                $(".reviewmsg div").addClass("errors");
                var status = '<li class="status">'+reviewFormMessages.status+'</li>';
                $('.errors ul').prepend(status);
                $('.errors').show().find('li.status').show().text(responce.msg);
            }
        }
        , error: function(){
            $('.reviewmsg div ul li').remove();
            $(".reviewmsg div").removeClass().addClass("errors");
            var unrecognizederror = '<li class="review-unrecognized-error">'+reviewFormMessages.reviewunrecognizederror+'</li>';
            $('.errors ul').prepend(unrecognizederror);
            $('.errors').show();
        }
    });
}

function publishReview(id){
    $('.reviewmsg div ul li').remove();
    $(".reviewmsg div").removeClass().addClass("success");
    var websiteUrl = $("#hid-main-wsurl").val();
    $('.success').ajaxStart(function(){
        $('.reviewmsg div ul li').remove();
        var proccessing = '<li class="proccessing">'+reviewFormMessages.proccessing+'</li>';
        $('.reviewmsg div ul').prepend(proccessing);
        $(this).show();
        
    })
    $.ajax({
          url: ''+websiteUrl+'sys/backend_ajax/publishreview/'
        , type: 'POST'
        , data: {id: id}
        , dataType: 'json'
        , success: function(responce){
            $('.reviewmsg div ul li').remove();
            if (responce.done){
                $('#review-'+responce.id).css({border:'none'}).find('.publishreview').remove();
                var status = '<li class="status">'+reviewFormMessages.status+'</li>';
                $('.success ul').prepend(status);
                $('.success').find('li.status').show().text('Review #'+responce.id+' published');
            } else {
                $(".reviewmsg div").removeClass().addClass("errors");
                var status = '<li class="status">'+reviewFormMessages.status+'</li>';
                $('.errors ul').prepend(status);
                $('.errors').show().find('li.status').show().text(responce.msg);
            }
        }
        , error: function(){
            $('.reviewmsg div ul li').remove();
            $(".reviewmsg div").removeClass().addClass("errors");
            var unrecognizederror = '<li class="review-unrecognized-error">'+reviewFormMessages.reviewunrecognizederror+'</li>';
            $('.errors ul').prepend(unrecognizederror);
            $('.errors').show();
        }
    });
}

function loadMoreReviews(productId){
    var websiteUrl = $("#hid-main-wsurl").val();
    $.ajax({
          url: ''+websiteUrl+'sys/backend_ajax/loadreviews/'
        , type: 'POST'
        , data: {productId:productId, offset: $('#reviews-for-product-'+productId).find('.hreview').size()}
        , dataType: 'json'
        , success: function(responce){
            //console.profile()
            if (responce.done){
                $('#reviews-for-product-'+productId).append(responce.data);
                if (undefined!==responce.last && responce.last==true){
                    $('#more-for-'+productId+'.morereviews').remove();
                }
            }
            //console.profileEnd()
        }
        , context: $(this)
    });
}